package netty.tcp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;


import java.nio.charset.Charset;

/**
 * @ClassName MyClientHandler
 * @Description TODO
 * @Author director吴
 * @Date 2022/4/22 13:33
 * @Version 1.0
 **/
public class MyClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private int count;


    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf buffer) throws Exception {
        byte[] bytes = new byte[buffer.readableBytes()];

        buffer.readBytes(bytes);
        String msg = new String(bytes, Charset.forName("utf-8"));
        System.out.println("客户端接收到的消息："+msg);
        System.out.println("客户端接收到的消息量："+(++this.count));




    }

    //发送数据
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //发送十次,模拟 粘包、拆包
        for(int i=0;i<10;i++){
            ByteBuf byteBuf = Unpooled.copiedBuffer("hello,server" + i, Charset.forName("utf-8"));

            ctx.writeAndFlush(byteBuf);

        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
